package com.aaa.oauth.security;

import com.aaa.oauth.entity.Manager;
import com.aaa.oauth.entity.TbAccAccount;
import com.aaa.oauth.service.impl.ManagerServiceImpl;
import com.aaa.oauth.service.impl.TbAccAccountServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class UserConfig implements UserDetailsService {

    @Resource
    ManagerServiceImpl managerServiceImpl;

    @Resource
    TbAccAccountServiceImpl accAccountServiceImpl;

    /**
     * 根据用户名加载用户信息
     * 登录时，会自动调用用户信息服务类中得方法，获取正确得用户信息，和表单提交得用户密码做匹配
     *
     * @param s 表单提交得用户名
     * @return 正确得用户信息
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s){
        System.out.println("s:"+s);

        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        List<Manager> list = managerServiceImpl.list(wrapper);

        QueryWrapper<TbAccAccount> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("phone",s);
        List<TbAccAccount> list2 = accAccountServiceImpl.list(wrapper2);

        if(list.size()==1){
            Manager manager = list.get(0);
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN,add");
            manager.setAuthorities(authorities);
            return manager;
        }else if (list2.size()==1){
            TbAccAccount tbAccAccount = list2.get(0);
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN,add");
            tbAccAccount.setAuthorities(authorities);
            return tbAccAccount;
        }
        else{
            throw new BadCredentialsException("用户名不存在");
        }
    }
}
